package com.cysd.ewmksbs.ksb_utils

import android.content.Context
import android.content.pm.PackageManager
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager

class FlashlightController(private val context: Context) {
    private var cameraId: String? = null
    private var isFlashlightOn = false
    private val cameraManager by lazy {
        context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
    }

    init {
        initializeCamera()
    }

    private fun initializeCamera() {
        try {
            cameraManager.cameraIdList.forEach { id ->
                val characteristics = cameraManager.getCameraCharacteristics(id)
                val hasFlash = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) ?: false
                if (hasFlash) {
                    cameraId = id
                    return@forEach
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun turnOnFlashlight(): Boolean {
        return try {
            cameraId?.let {
                cameraManager.setTorchMode(it, true)
                isFlashlightOn = true
                true
            } ?: false
        } catch (e: CameraAccessException) {
            when (e.reason) {
                CameraAccessException.CAMERA_IN_USE -> {
                    false // 返回false表示摄像头被占用
                }
                else -> {
                    e.printStackTrace()
                    false
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    fun turnOffFlashlight(): Boolean {
        return try {
            cameraId?.let {
                cameraManager.setTorchMode(it, false)
                isFlashlightOn = false
                true
            } ?: false
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    fun isFlashlightOn(): Boolean = isFlashlightOn

    fun isFlashAvailable(): Boolean {
        return try {
            context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
                    && cameraId != null
        } catch (e: Exception) {
            false
        }
    }


}